package com.pingxx.demo;

import com.pingxx.demo.util.ApplicationContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.cache.Cache;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * <p>
 * 缓存处理
 * </p>
 *
 * @author pingxx
 * @since 2020-04-26
 */
@Slf4j
public class MybatisRedisCache implements Cache {

    private static final long EXPIRE_TIME_IN_MINUTES = 30;

    private RedisTemplate<Object, Object> redisTemplate;

    private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    private String id;

    public MybatisRedisCache(String id) {
        if (id == null) {
            throw new IllegalArgumentException("Cache instances require an ID");
        }
        this.id = id;
    }

    @Override
    public String getId() {
        return id;
    }

    @Override
    public void putObject(Object o, Object o1) {
        try {
            this.getRedisTemplate().opsForValue().set(o, o1, EXPIRE_TIME_IN_MINUTES, TimeUnit.MINUTES);
        } catch (Exception e) {
            log.error("error", e);
        }
    }

    @Override
    public Object getObject(Object o) {
        try {
            return this.getRedisTemplate().opsForValue().get(o);
        } catch (Exception e) {
            log.error("error", e);
        }
        return null;
    }

    @Override
    public Object removeObject(Object o) {
        return this.getRedisTemplate().delete(o);
    }

    @Override
    public void clear() {
        this.getRedisTemplate().execute((RedisCallback) connection -> {
            connection.flushDb();
            return null;
        });
    }

    @Override
    public int getSize() {
        return 0;
    }

    private RedisTemplate getRedisTemplate() {
        return redisTemplate == null ? ApplicationContextHolder.getBean("redisTemplate") : redisTemplate;
    }
}
